package org.budo.support.java.awt.robot;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author limingwei
 */
public class BudoImageUtil {
    private static final Logger log = LoggerFactory.getLogger(BudoImageUtil.class);

    /**
     * 比较图片，如果图片相同则返回null
     */
    public static int[] firstDifferentPixel(BudoImage _this, BudoImage _that) {
        int w = _this.width();
        int h = _this.height();

        if (w != _that.width() || h != _that.height()) {
            log.error("#319 firstDifferentPixel, 图像大小 不同, _this=" + _this + ", _that=" + _that);
            return new int[] { -1, -1 };
        }

        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                if (_this.rgb(x, y) != _that.rgb(x, y)) {
                    return new int[] { x, y };
                }
            }
        }

        // 两图无区别
        return null;
    }

    public static void showBufferedImage(BufferedImage bufferedImage) {
        JFrame frame = new JFrame("BudoImage");
        frame.setSize(500, 500);

        frame.getContentPane().add(new JPanel() {
            private static final long serialVersionUID = 1239245052268403084L;

            public void paint(Graphics graphics) {
                super.paint(graphics);

                graphics.drawImage(bufferedImage, 0, 0, null);
            }
        });
        frame.setVisible(true);
    }

    public static BudoImageImpl default404() {
        BudoImageImpl budoImage = new BudoImageImpl(135, 35, BufferedImage.TYPE_INT_RGB);
        budoImage.graphics().antialias().color(Color.WHITE).fillRect();
        budoImage.graphics().red().drawString("404 - budo - image", 10, 20);
        return budoImage;
    }

    public static void showBudoImage(BudoImage budoImage) {
        BufferedImage bufferedImage = budoImage.getBufferedImage();
        showBufferedImage(bufferedImage);
    }
}